package com.dongzhu1428.express.module1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dongzhu1428.express.TIP;
import com.dongzhu1428.express.module1.Result;
import com.dongzhu1428.express.module1.dto.controllerDto.Message.GetAllConversationResultDto;
import com.dongzhu1428.express.module1.dto.controllerDto.Message.GetConversationDetailResultDto;
import com.dongzhu1428.express.module1.dto.controllerDto.Message.SendMessageParamDto;
import com.dongzhu1428.express.module1.entity.Message;
import com.dongzhu1428.express.module1.mapper.express.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Timestamp;

@Service
public class MessageService {
  @Autowired
    MessageMapper messageMapper;

  @Value("${imagePath}")
  String imagePath;
  public Result<TIP> sendMessage(SendMessageParamDto sendMessageParamDto) {


      String imgSrc =null;
      /**
       * 如果发的是图片信息
       */
      if(sendMessageParamDto.getImage()!=null){
          /**
           * 毫秒时间组成文件名，确保文件不会重复
           */
          imgSrc =imagePath+System.currentTimeMillis()+".jpg";

          /**
           * 保存图片到服务器
           */
          try {
              sendMessageParamDto.getImage().transferTo(new File(imgSrc));
          } catch (IOException e) {
              throw new RuntimeException(e);
          }
      }

      int type = 1;
      if(imgSrc ==null){
          type = 0;
      }
      else {
          imgSrc= imgSrc.replace("/home/ubuntu","");
      }
      messageMapper.insert(Message.builder()
                      .sender(sendMessageParamDto.getSender())
                      .text(sendMessageParamDto.getText())
                      .imgsrc(imgSrc)
                      .type(type)
                      .receiver(sendMessageParamDto.getReceiver())
                      .sendTime(new Timestamp(System.currentTimeMillis()))
              .build());

      return Result.success(TIP.成功);



  }

    /**
     * 得到所有谈话
     *
     * @param userId 用户id
     * @return {@link Result}<{@link GetAllConversationResultDto}>
     */
    public Result<GetAllConversationResultDto> getAllConversation( int userId){
        GetAllConversationResultDto getAllConversationResultDto = GetAllConversationResultDto.builder()
                .conversationList(messageMapper.getAllConversation(userId))
                .build();

        for (GetAllConversationResultDto.Conversation conversation : getAllConversationResultDto.getConversationList()) {
            if(conversation.getLastMessage() == null){
                conversation.setLastMessage("[图片]");
            }
        }
        return  Result.success(getAllConversationResultDto);
  }

  public Result<GetConversationDetailResultDto> getConversationDetail(int userId,int targetId){
        return  Result.success(GetConversationDetailResultDto.builder()
                .messageList(messageMapper.selectList(new QueryWrapper<Message>()
                                .eq("sender",userId)
                                .eq("receiver",targetId)
                                .or()
                                .eq("sender",targetId)
                                .eq("receiver",userId)
                                .last("order by id desc")
                        ))
                .build());
  }


  public Result<TIP>  markAllAsRead(int userId){
        messageMapper.update(null,new UpdateWrapper<Message>().eq("receiver",userId).set("`read`",true));
        return Result.success(TIP.成功);
  }
}
